﻿using System.Windows;
using Core;
using System.Xml;
using WeiBeeCommon.Core;
using Method = WeiBeeCommon.Core.Method;
using OAuthSina = WeiBeeCommon.Core.OAuthSina;
using Utility = WeiBeeCommon.Core.Utility;
using System.ComponentModel;

namespace Pages
{
    /// <summary>
    /// Interaction logic for SinaUser.xaml
    /// </summary>
    public partial class SinaUser : Window
    {
        public SinaUser()
        {
            InitializeComponent();
        }

        BackgroundWorker _bgwAuthLink;
        OAuthSina oAuth;
        string _user;
        string _pwd;
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                oAuth = new OAuthSina();
                _bgwAuthLink = new BackgroundWorker();
                _bgwAuthLink.DoWork += new DoWorkEventHandler(_bgwAuthLink_DoWork);
                _bgwAuthLink.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_bgwAuthLink_RunWorkerCompleted);
                _user = tbUsername.Text;
                _pwd = tbPassword.Password;
                _bgwAuthLink.RunWorkerAsync();
            }
            catch
            {
                MessageBox.Show(SettingHelper.MessageInvalidUserSettings);
                return;
            }
        }

        string authLink;
        void _bgwAuthLink_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            oAuth.SaveTokenAndTokenFunction = SaveTokenHelper.Saver;
            oAuth.SaveTokenAndTokenSecret();
            DialogResult = true;
            this.Close();
        }

        void _bgwAuthLink_DoWork(object sender, DoWorkEventArgs e)
        {
            authLink = oAuth.AuthorizationLinkGet();
            authLink += "&userId=" + _user + "&passwd=" + _pwd + "&oauth_callback=xml";

            string html = Utility.WebRequest(Method.POST, authLink, null);
            oAuth.AccessTokenGet(oAuth.Token, ParseHtml(html));
        }

        private string ParseHtml(string html)
        {
            XmlDocument xmldocument = new XmlDocument();
            xmldocument.LoadXml(html);
            return xmldocument.GetElementsByTagName("oauth_verifier")[0].InnerText;            
        }

        public OAuthBase GetOAuth()
        {
            return oAuth;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.tbUsername.Focus();
        }
    }
}
